package mk.company.fin.frame.internal;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import java.util.List;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;

import mk.company.fin.AppConstants;
import mk.company.fin.model.User;
import mk.company.fin.service.MessageService;
import mk.company.fin.service.ModelService;

import org.springframework.context.ApplicationContext;

public class UserFrame extends AbstractInternalFrame {

	private static final long serialVersionUID = 8930824031275692677L;
	
	/* SERVICES */
	
	private MessageService messageService;
	private ModelService modelService;

	
	//component which this frame will be drawn
	JComponent component;
	public UserFrame(JComponent component) {
		this.component=component;
		
	}
	
	@Override
	public void draw() {
		injectServices();
		initComponents();
	}
	
	@Override
	public void initialize(ApplicationContext context) {
		setContext(context);
		injectServices();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(new Dimension(AppConstants.MainFrame.WIDTH, AppConstants.MainFrame.HEIGHT));
		// components
		initComponents();
	}

	/**
	 * Inject services.
	 */
	private void injectServices() {
		messageService = getContext().getBean(MessageService.class);
		modelService=getContext().getBean(ModelService.class);
	}
	
	public void initComponents() {
		// title
		setTitle(messageService.getMessage("comintent.conto.plan"));
		// Size
		this.setSize(AppConstants.MainFrame.WIDTH, AppConstants.MainFrame.HEIGHT);
		// Maximize
		try {
			this.setMaximum(true);
		} catch (PropertyVetoException e) {
		} catch (NullPointerException n) {
		}
		
		// Layout
		this.setLayout(null);
		
		initUserPanel();
		
		initActionPanel();
		
		initUserTablePanel();
		
		userPanel.setVisible(false);
		
		//Set the layout of all the panels
		setLayout();
		
		this.setVisible(true);
		component.add(this);
	}
	
	private javax.swing.JTextField EMBGField;
    private javax.swing.JLabel EMBGLabel;
    private javax.swing.JCheckBox isActive;
    private javax.swing.JComboBox languageComboBox;
    private javax.swing.JLabel languageLabel;
    private javax.swing.JTextField nameField;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JLabel requiredLabel1;
    private javax.swing.JLabel requiredLabel2;
    private javax.swing.JLabel requiredLabel3;
    private javax.swing.JLabel requiredLabel4;
    private javax.swing.JTextField surnameField;
    private javax.swing.JLabel surnameLabel;
    private javax.swing.JButton userActionButton;
    private javax.swing.JPanel userPanel;
    private javax.swing.JTextField usernameField;
    private javax.swing.JLabel usernameLabel;
	private void initUserPanel(){
		userPanel = new javax.swing.JPanel();
		userPanel.setBorder(BorderFactory.createTitledBorder(messageService.getMessage("users.user")));
		nameLabel = new javax.swing.JLabel(messageService.getMessage("users.name"));
        nameField = new javax.swing.JTextField();
        nameField.setColumns(15);
        surnameField = new javax.swing.JTextField();
        surnameField.setColumns(15);
        surnameLabel = new javax.swing.JLabel(messageService.getMessage("users.surname"));
        usernameLabel = new javax.swing.JLabel(messageService.getMessage("users.username"));
        usernameField = new javax.swing.JTextField();
        usernameField.setColumns(15);
        isActive = new javax.swing.JCheckBox();
        isActive.setText(messageService.getMessage("users.active"));
        passwordField = new javax.swing.JPasswordField();
        passwordField.setColumns(15);
        passwordLabel = new javax.swing.JLabel(messageService.getMessage("users.password"));
        requiredLabel1 = new javax.swing.JLabel();
        requiredLabel2 = new javax.swing.JLabel();
        requiredLabel3 = new javax.swing.JLabel();
        requiredLabel4 = new javax.swing.JLabel();
        requiredLabel1.setForeground(new java.awt.Color(255, 0, 0));
        requiredLabel1.setText("*");
        requiredLabel2.setForeground(new java.awt.Color(255, 0, 0));
        requiredLabel2.setText("*");
        requiredLabel3.setForeground(new java.awt.Color(255, 0, 0));
        requiredLabel3.setText("*");
        requiredLabel4.setForeground(new java.awt.Color(255, 0, 0));
        requiredLabel4.setText("*");
        EMBGLabel = new javax.swing.JLabel(messageService.getMessage("users.EMBG"));
        EMBGField = new javax.swing.JTextField();
        EMBGField.setColumns(15);
        languageLabel = new javax.swing.JLabel(messageService.getMessage("users.language"));
        Vector<String> languages=new Vector<String>();
        languages.add("mk");languages.add("en");
        languageComboBox = new javax.swing.JComboBox(languages);
        userActionButton=new JButton();
        userActionButton.addActionListener(new ActionListener() {
			
			@SuppressWarnings("deprecation")
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if (nameField.getText().equals("")){
					JOptionPane.showMessageDialog(component, messageService.getMessage("users.messages.no.name"),"Error", JOptionPane.ERROR_MESSAGE);
					return;
				}
				if (surnameField.getText().equals("")){
					JOptionPane.showMessageDialog(component, messageService.getMessage("users.messages.no.surname"),"Error", JOptionPane.ERROR_MESSAGE);
					return;
				}
				if (usernameField.getText().equals("")){
					JOptionPane.showMessageDialog(component, messageService.getMessage("users.messages.no.username"),"Error", JOptionPane.ERROR_MESSAGE);
					return;
				}
				
				if (passwordField.getText().equals("")){
					JOptionPane.showMessageDialog(component, messageService.getMessage("users.messages.no.password"),"Error", JOptionPane.ERROR_MESSAGE);
					return;
				}
				if (userActionButton.getText().equals(messageService.getMessage("organization.sector.action.add"))){
					User user=new User();
					user.setFirstName(nameField.getText());
					user.setLastName(surnameField.getText());
					user.setUsername(usernameField.getText());
					user.setPassword(passwordField.getText());
					user.setEmbg(EMBGField.getText());
					user.setLanguage(languageComboBox.getSelectedItem()+"");
					user.setActive(isActive.isSelected());
					try {
						modelService.update(user);
						clearData();
						userPanel.setVisible(false);
						refreshTableData();
					}
					catch (Exception ex){
						JOptionPane.showMessageDialog(component, messageService.getMessage("users.messages.cannot.be.added"),"Error", JOptionPane.ERROR_MESSAGE);
					}
				}
				if (userActionButton.getText().equals(messageService.getMessage("organiazation.sector.action.save"))){
					if (selectedUser!=null){
						selectedUser.setFirstName(nameField.getText());
						selectedUser.setLastName(surnameField.getText());
						selectedUser.setUsername(usernameField.getText());
						selectedUser.setPassword(passwordField.getText());
						selectedUser.setEmbg(EMBGField.getText());
						selectedUser.setLanguage(languageComboBox.getSelectedItem()+"");
						selectedUser.setActive(isActive.isSelected());
						try {
							modelService.update(selectedUser);
							userPanel.setVisible(false);
							refreshTableData();
						}
						catch (Exception ex) {
							JOptionPane.showMessageDialog(component, messageService.getMessage("users.messages.cannot.be.update"),"Error", JOptionPane.ERROR_MESSAGE);
							modelService.refresh(selectedUser);
						}
					}
				}
				
			}
		});
	}
	
	private javax.swing.JPanel actionPanel;
	private javax.swing.JButton addUserButton;
	private javax.swing.JButton modifyUserButton;
	private User selectedUser;
	private void initActionPanel() {
		actionPanel=new JPanel();
		actionPanel.setBorder(BorderFactory.createTitledBorder(messageService.getMessage("organization.sector.action")));
  	  	addUserButton=new JButton();
  	  	addUserButton.setText(messageService.getMessage("users.new"));
  	  	modifyUserButton=new JButton();
  	  	modifyUserButton.setText(messageService.getMessage("users.modify"));
  	  	addUserButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				userActionButton.setText(messageService.getMessage("organization.sector.action.add"));
				userPanel.setVisible(true);
				clearData();
			}
		});
  	  	
  	  	modifyUserButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				if (userTable.getSelectedRow()>=0){
					int rowIndex=userTable.convertRowIndexToModel(userTable.getSelectedRow());
					selectedUser=userList.get(rowIndex);
					userActionButton.setText(messageService.getMessage("organiazation.sector.action.save"));
					nameField.setText(selectedUser.getFirstName());
					surnameField.setText(selectedUser.getLastName());
					usernameField.setText(selectedUser.getUsername());
					passwordField.setText(selectedUser.getPassword());
					EMBGField.setText(selectedUser.getEmbg());
					isActive.setSelected(selectedUser.isActive());
					languageComboBox.setSelectedItem(selectedUser.getLanguage());
					userPanel.setVisible(true);
				}
			}
		});
	}
	
	private javax.swing.JTable userTable;
	private javax.swing.JPanel userTablePanel;
	private DefaultTableModel userTableModel;
	private javax.swing.JScrollPane userTableScrollPane;
	private List<User> userList;
	@SuppressWarnings("all")
	private void initUserTablePanel() {
		userTablePanel=new JPanel();
		userTablePanel.setBorder(BorderFactory.createTitledBorder(messageService.getMessage("users.list")));
		userTableScrollPane = new javax.swing.JScrollPane();
		userTable = new javax.swing.JTable();
		userTableModel=new javax.swing.table.DefaultTableModel(
	            new Object [][] {
	            },
	            new String [] {
	            	messageService.getMessage("users.name"),messageService.getMessage("users.surname"),
	            	messageService.getMessage("users.username"),messageService.getMessage("users.EMBG"),
	            	messageService.getMessage("users.language"),messageService.getMessage("users.active")
	            }
	        ) {
	            Class[] types = new Class [] {
	                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
	            };
	            boolean[] canEdit = new boolean [] {
	                false, false, false, false, false, false
	            };

	            public Class getColumnClass(int columnIndex) {
	                return types [columnIndex];
	            }

	            public boolean isCellEditable(int rowIndex, int columnIndex) {
	                return canEdit [columnIndex];
	            }
	        };
	        userTable.setModel(userTableModel);
	        userTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
	        userTable.setAutoCreateRowSorter(true);
	        userTableScrollPane.setViewportView(userTable);
	        refreshTableData();
	}
	
	private void refreshTableData(){
		userList=modelService.findAll(User.class);
		userTableModel.getDataVector().removeAllElements();
		userTable.setAutoCreateRowSorter(true);
		for (User user:userList){
			Vector<String> row=new Vector<String>();
			row.add(user.getFirstName());
			row.add(user.getLastName());
			row.add(user.getUsername());
			row.add(user.getEmbg());
			row.add(user.getLanguage());
			if (user.isActive())
				row.add(messageService.getMessage("user.is.active"));
			else
				row.add(messageService.getMessage("user.not.ative"));
			userTableModel.addRow(row);
		}
	}
	private void clearData(){
		nameField.setText("");
		surnameField.setText("");
		usernameField.setText("");
		passwordField.setText("");
		EMBGField.setText("");
		languageComboBox.setSelectedIndex(0);
		isActive.setSelected(true);
	}
	
	private void setLayout(){
		javax.swing.GroupLayout userPanelLayout = new javax.swing.GroupLayout(userPanel);
        userPanel.setLayout(userPanelLayout);
        userPanelLayout.setHorizontalGroup(
            userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(userPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(nameLabel)
                    .addComponent(surnameLabel)
                    .addComponent(usernameLabel)
                    .addComponent(passwordLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(userPanelLayout.createSequentialGroup()
                        .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(requiredLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(EMBGLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(EMBGField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, userPanelLayout.createSequentialGroup()
                            .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(requiredLabel3)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(userActionButton))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, userPanelLayout.createSequentialGroup()
                            .addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(userPanelLayout.createSequentialGroup()
                                    .addComponent(surnameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(requiredLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, userPanelLayout.createSequentialGroup()
                                    .addComponent(usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(requiredLabel4)))
                            .addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(userPanelLayout.createSequentialGroup()
                                    .addGap(18, 18, 18)
                                    .addComponent(isActive))
                                .addGroup(userPanelLayout.createSequentialGroup()
                                    .addGap(18, 18, 18)
                                    .addComponent(languageLabel)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(languageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                .addContainerGap(55, Short.MAX_VALUE))
        );
        userPanelLayout.setVerticalGroup(
            userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(userPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nameLabel)
                    .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(requiredLabel1)
                    .addComponent(EMBGLabel)
                    .addComponent(EMBGField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(surnameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(surnameLabel)
                    .addComponent(requiredLabel2)
                    .addComponent(languageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(languageLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(usernameLabel)
                    .addComponent(requiredLabel4)
                    .addComponent(isActive))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(passwordLabel)
                    .addComponent(requiredLabel3)
                    .addComponent(userActionButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        javax.swing.GroupLayout actionPanelLayout = new javax.swing.GroupLayout(actionPanel);
        actionPanel.setLayout(actionPanelLayout);
        actionPanelLayout.setHorizontalGroup(
            actionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(actionPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(addUserButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(modifyUserButton)
                .addContainerGap(18, Short.MAX_VALUE))
        );
        actionPanelLayout.setVerticalGroup(
            actionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(actionPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(actionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addUserButton)
                    .addComponent(modifyUserButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        javax.swing.GroupLayout userTablePanelLayout = new javax.swing.GroupLayout(userTablePanel);
        userTablePanel.setLayout(userTablePanelLayout);
        userTablePanelLayout.setHorizontalGroup(
            userTablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(userTablePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(userTableScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 509, Short.MAX_VALUE)
                .addContainerGap())
        );
        userTablePanelLayout.setVerticalGroup(
            userTablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(userTablePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(userTableScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(userTablePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(actionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(userPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(userPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(actionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(userTablePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(244, Short.MAX_VALUE))
        );
	}
	

}
